import React from 'react'
import { createBehavior, createResource } from '@designable/core'
import {
  DnFC,
  useNodeIdProps,
  useTreeNode,
  TreeNodeWidget,
  DroppableWidget,
} from '@designable/react'
import { TreeNode } from '@designable/core'
import { matchComponent } from '../../shared'
import { createVoidFieldSchema } from '../Field'
import { AllSchemas } from '../../schemas'
import { AllLocales } from '../../locales'
import { DetailHeader as CustomDetailHeader } from '../../customComponents'

// 解析按钮节点
const parseButtons = (parent: TreeNode) => {
  const buttons: TreeNode[] = []
  parent.children.forEach((node) => {
    if (matchComponent(node, 'Button')) {
      buttons.push(node)
    }
  })
  return buttons
}

export const DetailHeader: DnFC<{
  title: string
  style?: React.CSSProperties
  titleKey: string
  statusKey: string
  statusNameKey: string
  statusColorExpression: string
}> = (props) => {
  const {
    title,
    style,
    titleKey,
    statusKey,
    statusNameKey,
    statusColorExpression,
  } = props
  const nodeId = useNodeIdProps()
  const node = useTreeNode()

  // 解析拖拽传入的按钮
  const buttons = parseButtons(node)

  return (
    <div {...nodeId}>
      <CustomDetailHeader
        title={title}
        style={style}
        titleKey={titleKey}
        statusKey={statusKey}
        statusNameKey={statusNameKey}
        statusColorExpression={statusColorExpression}
      >
        {buttons.length > 0 ? (
          buttons.map((button) => (
            <TreeNodeWidget key={button.id} node={button} />
          ))
        ) : (
          <DroppableWidget />
        )}
      </CustomDetailHeader>
    </div>
  )
}

DetailHeader.Behavior = createBehavior({
  name: 'DetailHeader',
  extends: ['Field'],
  selector: (node) => node.props['x-component'] === 'DetailHeader',
  designerProps: {
    droppable: true,
    allowAppend: (target, source) => {
      // 只允许拖拽Button组件
      return source.every((node) => node.props['x-component'] === 'Button')
    },
    propsSchema: createVoidFieldSchema(AllSchemas.DetailHeader),
  },
  designerLocales: AllLocales.DetailHeader,
})

DetailHeader.Resource = createResource({
  icon: 'DetailHeaderSource',
  elements: [
    {
      componentName: 'Field',
      props: {
        type: 'void',
        title: 'DetailHeader',
        'x-component': 'DetailHeader',
        'x-component-props': {
          title: '标题',
          titleKey: 'orderNo',
          statusKey: 'orderStatus',
          statusNameKey: 'orderStatusName',
          statusColorExpression: '',
        },
      },
    },
  ],
})
